package com.Filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.hutool.core.util.StrUtil;
import com.Common.CodeMsg;
import com.Common.Constant;
import com.Common.Result;
import com.Util.RespUtil;

/**
 * @ClassName: LoginFilter 
 * @Description: 登录过滤器
 * @author: Mr.T
 * @date: 2019年9月16日 下午2:50:47
 */

@WebFilter(urlPatterns = {"*.do","*.jsp"})
public class LoginFilter implements  Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		//判断是否是  ajax 请求
		boolean isAjaxRequest = false;
		String ajaxHeader = req.getHeader("x-requested-with");
		if(StrUtil.equals(ajaxHeader, "XMLHttpRequest")) {
			 isAjaxRequest = true;  
		}
		
		//获取当前用户
		HttpSession session = req.getSession();
		Object obj = session.getAttribute(Constant.CURRENT_USER);
		
		
		if(obj != null) {
			chain.doFilter(request, response);
		}else {
			/**
			 * 	如果是 登录页面   注册页面  验证码   登录 servlet  注册 servlet  放行
			 */
			//获取请求  uri
			String  uri = req.getRequestURI();
			// 登录页面 或者 注册页面 放行
			if(uri.endsWith("index.jsp")) {
				chain.doFilter(request, response);
				return;
			}
			//登录servlet 或者是  注册servlet 放行
			String type = req.getParameter("type");
			if(uri.endsWith("user.do")) {
				if("login".equals(type)) {
					chain.doFilter(request, response);
					return;
				}
			}
			//此时 session 是空的  且 用户是ajax 请求
			if(obj == null && isAjaxRequest) {
				RespUtil.write(resp, new Result(CodeMsg.USER_SESSION_INVALI_ERROR));
				return;
			}
			//其他情况  返回登录页面
			resp.sendRedirect("index.jsp");
		}
	}

	
	@Override
	public void destroy() {
		
	}

}
